﻿namespace BadHabit.WPFTools
{
    using System.Windows;
    using System.Windows.Media;

    public class Helper
    {
        /// <summary>
        /// Gets the element visual parent of a given type.
        /// </summary>
        /// <typeparam name="T">Type of the element</typeparam>
        /// <param name="element">The element</param>
        /// <returns>The element´s visual parent of the type T</returns>
        public static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }

            return null;
        }
    }
}
